<?php

namespace App\Model;

class  Menu extends BaseModel
{
    /**
     * 获取菜单列表
     * @param $where
     * @param string $columns
     * @return array
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\Option
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function getMenuList($where, $columns = '*')
    {
        $condition = $this->analysisWhere($where);
        return $this->getAll($condition, $columns);
    }

    /**
     * 获取单个菜单
     * @param $where
     * @return \EasySwoole\Mysqli\Mysqli|mixed|null
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function getInfo($where)
    {
        return $this->findOne($where);
    }

    /**
     * 返回树节点
     * @param bool $tree
     * @param $request
     * @return array|mixed|\PDOStatement|string|\think\Collection|\type
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getReturnNode($tree = TRUE, $data)
    {
        static $tree_nodes = array();
        if ($tree && !empty($tree_nodes[(int)$tree])) {
            return $tree_nodes[$tree];
        }
        if ((int)$tree) {
            $list = $this->getAll([],'id,pid,title,url,tip,hide');
            foreach ($list as $key => $value) {
                if (stripos($value['url'], $data['module']) !== 0) {
                    $list[$key]['url'] = strtolower($data['module'] . '/' . $value['url']);
                }
            }
            $nodes = list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'operator', $root = 0);
            foreach ($nodes as $key => $value) {
                if (!empty($value['operator'])) {
                    $nodes[$key]['child'] = $value['operator'];
                    unset($nodes[$key]['operator']);
                }
            }
        } else {
            $nodes = $this->getAll($this->analysisWhere(['sort|order'=>'asc']),'title,url,tip,pid');
            foreach ($nodes as $key => $value) {
                if (stripos($value['url'], $data['module']) !== 0) {
                    $nodes[$key]['url'] = strtolower($data['module'] . '/' . $value['url']);
                }
            }
        }

        return $nodes;
    }
}